package com.baizhi.cmfz.service.impl;


import com.alibaba.fastjson.JSON;
import com.baizhi.cmfz.dao.UserDao;
import com.baizhi.cmfz.service.ThreadUserService;
import com.baizhi.cmfz.util.ThreadPollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ThreadUserServcieImpl implements ThreadUserService {

    @Autowired
    private UserDao dao;

    @Override
    public Map getAllCountByCountDownLatch() throws Exception {
        //线程安全的ConcurrentHashMap
        ConcurrentHashMap map = new ConcurrentHashMap();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        System.out.println("创建CountDownLatch的计数：" + countDownLatch.getCount());
        ThreadPoolExecutor executor = ThreadPollUtil.executor;

        System.out.println("ThreadPollUtil.getCorePoolSize:  " + ThreadPollUtil.getCorePoolSize());



        //查询注册量
        executor.submit(new Runnable() {
            @Override
            public void run() {
                int[] ints = new int[3];
                ints[0] = dao.selectByDayCount(7, 0);
                ints[1] = dao.selectByDayCount(14, 7);
                ints[2] = dao.selectByDayCount(21, 14);
                map.put("count",ints);
                countDownLatch.countDown();
                System.out.println("countDownLatch.getCount()---  "  + countDownLatch.getCount());
            }
        });
        //查询男女比例
        executor.submit(new Runnable() {
            @Override
            public void run() {
                List<Map> list = dao.selectBySexCount();
                map.put("sex",list);
                countDownLatch.countDown();
                System.out.println("countDownLatch.getCount()---  "  + countDownLatch.getCount());
            }
        });
        //查询省份信息
        executor.submit(new Runnable() {
            @Override
            public void run() {
                List<Map> list = dao.selectByProvince();
                map.put("province",list);
                countDownLatch.countDown();
                System.out.println("countDownLatch.getCount()---  "  + countDownLatch.getCount());
            }
        });
        //主线程等待，直到计数器为0；
        countDownLatch.await();
        System.out.println("over:"  + countDownLatch.getCount());
        System.out.println(JSON.toJSONString("map:  " + map));


        return map;
    }
}
